package com.synjones.ui.others;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.synjones.entry.SignPerson;
import com.synjones.idcardusb_reader.R;
import com.synjones.ui.FirstScreenRouter;
import com.synjones.ui.SecondScreenRouter;
import com.synjones.util.DateTimeUtil;

import java.util.ArrayList;
import java.util.List;

public class OthersSecondScreen extends FrameLayout implements OthersContract.View {

    private OthersContract.Presenter presenter;


    public static final int DO_SIGN_OTHER = 0;
    public static final int DO_SIGN_SELF = 1;

    private int doWhat;
    private String idno;
    private String idname;

    private EditText othersInput;

    private Button othersQuery;

    private Button othersSign;
    private Button othersCancel;

    private RecyclerView recyclerView;

    private View othersNotFind;

    private View othersSearchBar;


    private List<SignPerson> searchResult = new ArrayList<>();

    private SignPerson selectPerson;


    private FirstScreenRouter router1;
    private SecondScreenRouter router2;


    private OtherPersonAdapter otherPersonAdapter =
            new OtherPersonAdapter(R.layout.others_list_item, new ArrayList<SignPerson>());



    public OthersSecondScreen(@NonNull Context context,int doWhat,String idno,
                              String idname,FirstScreenRouter router1,SecondScreenRouter router2) {
        super(context);
        this.doWhat = doWhat;
        this.idno = idno;
        this.idname = idname;
        this.router1 = router1;
        this.router2 = router2;
        presenter = new OthersSecPresenter(this, router1);
        View view =  LayoutInflater.from(context).inflate(R.layout.fragment_others, null);
        intView(view);
        addView(view,new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        setRecyclerView();
    }



    private void setRecyclerView(){
        otherPersonAdapter.setHeaderView(LayoutInflater.from(getContext()).inflate(R.layout.others_list_header,null));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        otherPersonAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (SignPerson sp:searchResult) { sp.setSelected(false); }
                selectPerson = searchResult.get(position);
                selectPerson.setSelected(true);
                otherPersonAdapter.setNewData(searchResult);
                othersSign.setVisibility(View.VISIBLE);
            }
        });
        recyclerView.setAdapter(otherPersonAdapter);
    }


    private void intView(View view){
        othersInput = (EditText) view.findViewById(R.id.othersInput);
        othersQuery = (Button) view.findViewById(R.id.othersQuery);
        othersSign = (Button) view.findViewById(R.id.othersSign);
        othersCancel= (Button) view.findViewById(R.id.othersCancel);
        recyclerView = (RecyclerView) view.findViewById(R.id.othersList);
        othersNotFind = view.findViewById(R.id.othersNotFind);
        othersSearchBar = view.findViewById(R.id.othersSearchBar);
        if (doWhat == DO_SIGN_OTHER){
            othersSearchBar.setVisibility(View.VISIBLE);
        }else {
            othersSearchBar.setVisibility(View.INVISIBLE);
            showSearchResult(searchResult);
        }
        othersSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //自己签到和代签穿的数据不同
                if (doWhat == DO_SIGN_SELF){
                    presenter.sign("1","", "",
                            selectPerson.getInvitationCode(),idno,selectPerson);
                }else {
                    presenter.sign("0",idname, idno,
                            selectPerson.getInvitationCode(),"",selectPerson);
                }
            }
        });
        othersCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                router1.gotoWelcome();
                router2.gotoWelcome();
            }
        });

        othersQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppCompatActivity activity = (AppCompatActivity) router1;
                //隐藏键盘
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
                //Find the currently focused view, so we can grab the correct window token from it.
                View view =activity.getCurrentFocus();
                //If no view currently has focus, create a new one, just so we can grab a window token from it
                if (view == null) { view = new View(getContext()); }
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                //搜索
                String inputInfo = othersInput.getText().toString();
                if (!TextUtils.isEmpty(inputInfo)) presenter.search(inputInfo);
            }
        });
    }
    @Override
    public void showSearchResult(List<SignPerson> resultList) {
        searchResult = sortData(resultList);
        if (searchResult.isEmpty()){
            othersSign.setVisibility(View.GONE);
            othersNotFind.setVisibility(View.VISIBLE);
        }else {
            othersNotFind.setVisibility(View.GONE);
            if (searchResult.size() ==1){
                othersSign.setVisibility(View.VISIBLE);
                selectPerson = searchResult.get(0);
            }
            else
                othersSign.setVisibility(View.GONE);
        }
        if (searchResult.size() == 1) searchResult.get(0).setSelected(true);
        otherPersonAdapter.setNewData(searchResult);
    }

    private List<SignPerson> sortData(List<SignPerson> signPeople){
        List<SignPerson> rlt = new ArrayList<>();
        for (SignPerson sp: signPeople) {
            if (TextUtils.isEmpty(sp.getSignTime())) rlt.add(0, sp);
            else rlt.add(sp);
        }
        return rlt;
    }
    @Override
    public void showBackInfo(String msg, int color) {
        router1.showToast(msg,color);
        router2.showToast(msg,color);
    }

    @Override
    public void updateSignTime(SignPerson signPerson) {
        for (SignPerson sp: searchResult) {
            if (sp.getInvitationCode().equals(signPerson.getInvitationCode()))
                sp.setSignTime(DateTimeUtil.getFormatCurrentTime());
        }
        showSearchResult(searchResult);
    }
}
